package org.qpcr.community.project.web.excel;

import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import org.hswebframework.reactor.excel.CellDataType;
import org.hswebframework.reactor.excel.ExcelHeader;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.bean.FastBeanCopier;
import org.hswebframework.web.validator.ValidatorUtils;
import org.qpcr.community.project.model.entity.ExperimentalRecordsInstanceEntity;
import org.qpcr.core.metadata.Jsonable;

import javax.validation.constraints.NotBlank;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
@Setter
public class ExperimentalRecordsExcelInfo implements Jsonable {

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "检测项")
    @NotBlank(message = "检测项不能为空")
    private String item;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "检测时间")
    @NotBlank(message = "检测时间不能为空")
    private String receiveTime;

//    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "数据源")
//    @NotBlank(message = "数据源不能为空")
//    private String dataSource;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "载体信息")
    @NotBlank(message = "载体信息不能为空")
    private String carrier;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "试剂编号")
    @NotBlank(message = "试剂编号不能为空")
    private String reagentNumber;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "状态")
    @NotBlank(message = "状态不能为空")
    private String state;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "运行时长")
    @NotBlank(message = "运行时长不能为空")
    private String runTime;

    @org.qpcr.community.io.excel.annotation.ExcelHeader(value = "设备编号")
    @NotBlank(message = "设备编号不能为空")
    private String deviceId;

    private ExperimentalRecordsInstanceEntity testItemInstance;

    private long rowNumber;

    public Map<String,Object> toMap(){
        Map<String, Object> result = FastBeanCopier.copy(this, new HashMap<>());

        // 格式化检测时间：从时间戳转换为 yyyy-MM-dd HH:mm:ss 格式
        if (receiveTime != null && !receiveTime.isEmpty()) {
            try {
                long timestamp = Long.parseLong(receiveTime);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                result.put("receiveTime", sdf.format(new Date(timestamp)));
            } catch (NumberFormatException e) {
                // 如果不是时间戳格式，保持原值
                result.put("receiveTime", receiveTime);
            }
        }

        // 格式化状态：在数值后添加 % 符号
        if (state != null && !state.isEmpty()) {
            try {
                // 尝试解析为数字，如果是数字则添加%
                Double.parseDouble(state);
                result.put("state", state + "%");
            } catch (NumberFormatException e) {
                // 如果不是数字格式，保持原值
                result.put("state", state);
            }
        }

        // 格式化运行时长：从毫秒转换为 xx分xx秒 格式
        if (runTime != null && !runTime.isEmpty()) {
            try {
                long millis = Long.parseLong(runTime);
                int seconds = (int) (millis / 1000) % 60; // 计算秒数
                int minutes = (int) (millis / 60000); // 计算分钟
                result.put("runTime", minutes + "分" + seconds + "秒");
            } catch (NumberFormatException e) {
                // 如果不是数字格式，保持原值
                result.put("runTime", runTime);
            }
        }

        return result;
    }

    public static List<ExcelHeader> getTemplateHeaderMapping(ExperimentalRecordsExcelFilterColumns filterColumns) {
        return Arrays.stream(new ExcelHeader[]{
                new ExcelHeader("id", "物模型标识", CellDataType.STRING),
                new ExcelHeader("name", "物模型名称", CellDataType.STRING),
                new ExcelHeader("value", "值", CellDataType.STRING)
            })
            .filter(a-> !filterColumns.getColumns().contains(a.getKey()))
            .collect(Collectors.toList());
    }

    public static List<ExcelHeader> getExportHeaderMapping(ExperimentalRecordsExcelFilterColumns filterColumns) {
        return Arrays.stream(new ExcelHeader[]{
                new ExcelHeader("item", "检测项", CellDataType.STRING),
                new ExcelHeader("receiveTime", "检测时间", CellDataType.STRING),
//                new ExcelHeader("dataSource", "数据源", CellDataType.STRING),
                new ExcelHeader("carrier", "载体信息", CellDataType.STRING),
                new ExcelHeader("reagentNumber", "试剂编号", CellDataType.STRING),
                new ExcelHeader("state", "状态", CellDataType.STRING),
                new ExcelHeader("runTime", "运行时长", CellDataType.STRING),
                new ExcelHeader("deviceId", "设备编号", CellDataType.STRING)
            })
            .filter(a-> !filterColumns.getColumns().contains(a.getKey()))
            .collect(Collectors.toList());
    }

    /**
     * 初始化保存实体
     *
     * @param testItemInstanceListDb 数据库已存在的数据
     * @param auth 认证数据
     * @return ExperimentalRecordsExcelInfo
     */
    public ExperimentalRecordsExcelInfo initExperimentalRecordsInstance(List<ExperimentalRecordsInstanceEntity> testItemInstanceListDb, Authentication auth) {
        ExperimentalRecordsInstanceEntity entity = FastBeanCopier.copy(this, new ExperimentalRecordsInstanceEntity());

        entity.setCreateTimeNow();
        entity.setCreatorId(auth.getUser().getId());
        entity.setCreatorName(auth.getUser().getName());

        entity.setModifyTimeNow();
        entity.setModifierId(auth.getUser().getId());
        entity.setModifierName(auth.getUser().getName());

        ValidatorUtils.tryValidate(entity);

        this.testItemInstance = entity;
        return this;
    }

    @Override
    public void fromJson(JSONObject json) {
        Jsonable.super.fromJson(json);
    }
}
